<?php
session_start();
include_once "../apps/ManagerIUDS.php";
$managerIUDS = new ManagerIUDS();

$productName = $_POST["product_name"];
$productDetail = $_POST["product_detail"];
$imageName=$_FILES['file']['name'];
$oldName=$_POST['link'];

$productId = $_GET["product_id"];
if($productId == "" || $productId == null){
	$productId = $_POST["product_id"];
}

$mode = $_GET["mode"];
if($mode == "" || $mode == null){
	$mode = $_POST["mode"];
}

$page = $_GET['page'];
if (!isset($page) && $page == "") {
	$page = 1;
}
$path ="productImage";
if($mode == "insert"){
	move_uploaded_file($_FILES["file"]["tmp_name"],"../".$path."/" . $imageName);
	$arrData["product_name"] = "".$productName."";
	$arrData["product_detail"] ="".$productDetail."";
	$arrData["product_pic_name"] ="".$imageName."";
	$arrData["create_date"] = "".date("Y-m-d")."";
	$arrData["create_by"] = "".$_SESSION["user_name"]."";
	$managerIUDS->inserData($arrData, "product");
	header("Location:../contents/product_main.php");
}else if($mode == "delete"){
	$arrPrimaryKey["product_id"] = "".$productId."";
	$productPicName=$_GET["product_pic_name"];
	
		if (file_exists("../".$path."/".$productPicName)) {
			unlink("../".$path."/".$productPicName);
		} 
		
	$managerIUDS->deleteData("product", $arrPrimaryKey, "");
	header("Location:../contents/product_main.php");
}else if($mode == "update"){
	
	if($imageName != null && $imageName != ""){
		if (file_exists("../".$path."/".$oldName)) {
			unlink("../".$path."/".$oldName);
		} 
		move_uploaded_file($_FILES["file"]["tmp_name"],"../".$path."/" . $imageName);
		$imageName = "../".$path."/". $imageName;
	}else{
		$imageName =$oldName;
	}
	
	$arrData["product_name"] = "".$productName."";
	$arrData["product_detail"] ="".$productDetail."";
	$arrData["product_pic_name"] ="".$imageName."";
	$arrData["update_date"] = "".date("Y-m-d")."";
	$arrData["update_by"] = "".$_SESSION["user_name"]."";
	$arrPrimaryKey["product_id"] = "".$productId."";
	//print_r($arrData);
	$managerIUDS->updateData($arrData, "product", $arrPrimaryKey, "");
	header("Location:../contents/product_main.php");
}else if($mode == "search"){
	$productName = $_GET["product_name"];
	header("Location:../contents/product_main.php?mode=search&page=".$page."&product_name=".urlencode($productName));
}else if($mode == "searchProductList"){
	$productName = $_GET["product_name"];
	header("Location:../contents/product_list.php?mode=search&page=".$page."&product_name=".urlencode($productName));
}else if($mode == "listProductData"){
	$productData = array();
	$productName = $_GET["product_name"];
	if($productName == "" || $productName == null){
		$productName = $_POST["product_name"];
	}
	$productData = $managerIUDS->queryData("product_name", "product", " WHERE product_name LIKE '%".$breedName."%'", "2", "");
	if(sizeof($productData)<=0){
		$productData = "";
	}
	echo json_encode($productData);
}
?>